package com.xky.ui.module.customersManagement.update;

import com.xky.pojo.Customers;
import com.xky.utils.DBUtils;
import com.xky.ui.module.customersManagement.select.SelectCustomers;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 修改客户信息的窗口类
 */
public class UpdateCustomer extends JFrame {
    private JPanel mainPanel, formPanel, buttonPanel;
    private JTextField idField, codeField, nameField, contactPersonField, 
                      phoneField, emailField, addressField, creditLimitField;
    private JCheckBox isActiveCheckBox;
    private JButton searchButton, updateButton, cancelButton;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color CANCEL_BUTTON_COLOR = new Color(231, 76, 60);
    
    // 邮箱验证正则表达式
    private static final String EMAIL_REGEX =
            "^(?![._-])(?!.*[._-]$)(?!.*\\.\\.)[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@(?![-])(?!.*-$)[a-zA-Z0-9-]+\\.[a-zA-Z]{2,}(?:\\.[a-zA-Z]{2,})?$";

    public UpdateCustomer() {
        setTitle("修改客户信息");
        setSize(550, 800);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        init();
        setVisible(true);
    }

    private void init() {
        // 创建主面板并设置背景渐变
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 顶部标题面板
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("修改客户信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        hintPanel.setOpaque(false);
        
        JLabel hintLabel = new JLabel("请输入客户ID查询后再修改");
        hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        hintLabel.setForeground(Color.GRAY);
        hintPanel.setPreferredSize(new Dimension(100,30));
        hintPanel.add(hintLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(hintPanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        // 中部搜索和表单面板
        JPanel centerPanel = new JPanel(new BorderLayout(0, 15));
        centerPanel.setOpaque(false);
        
        // 搜索面板
        JPanel searchCard = createRoundedPanel();
        searchCard.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15));
        
        JLabel idLabel = new JLabel("客户ID");
        idLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        idLabel.setForeground(PRIMARY_COLOR);
        searchCard.add(idLabel);
        
        idField = new JTextField(15);
        idField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        idField.setPreferredSize(new Dimension(200, 35));
        searchCard.add(idField);
        
        searchButton = new JButton("查询");
        styleButton(searchButton, QUERY_BUTTON_COLOR);
        searchButton.setPreferredSize(new Dimension(100, 35));
        searchCard.add(searchButton);
        
        centerPanel.add(searchCard, BorderLayout.NORTH);

        // 表单面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        
        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        
        // 创建表单字段
        createFormFields(formPanel);

        formCard.add(formPanel, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        centerPanel.add(formCard, BorderLayout.CENTER);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        
        // 底部按钮面板
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);
        
        updateButton = new JButton("更新");
        styleButton(updateButton, BUTTON_COLOR);
        
        cancelButton = new JButton("取消");
        styleButton(cancelButton, CANCEL_BUTTON_COLOR);
        
        buttonPanel.add(updateButton);
        buttonPanel.add(cancelButton);
        
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
        
        // 禁用表单字段，直到用户搜索到客户
        setFormFieldsEnabled(false);
        
        // 添加事件监听器
        addEventListeners();
    }

    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);

        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));

        return panel;
    }
    
    private void styleButton(JButton button, Color bgColor) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
    }
    
    /**
     * 创建表单字段
     */
    private void createFormFields(JPanel panel) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 10, 10);
        
        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);
        
        JLabel[] labels = new JLabel[]{
                new JLabel("客户编码 *"),
                new JLabel("客户名称 *"),
                new JLabel("联系人 *"),
                new JLabel("联系电话 *"),
                new JLabel("电子邮箱 *"),
                new JLabel("联系地址 *"),
                new JLabel("信用额度 *"),
                new JLabel("是否有效")
        };
        
        // 创建文本字段
        codeField = new JTextField(20);
        nameField = new JTextField(20);
        contactPersonField = new JTextField(20);
        phoneField = new JTextField(20);
        emailField = new JTextField(20);
        addressField = new JTextField(20);
        creditLimitField = new JTextField(20);
        isActiveCheckBox = new JCheckBox();
        isActiveCheckBox.setOpaque(false);
        
        JTextField[] fields = {codeField, nameField, contactPersonField, phoneField, emailField, addressField, creditLimitField};
        
        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.weightx = 0.3;
            labels[i].setFont(labelFont);
            labels[i].setForeground(PRIMARY_COLOR);
            panel.add(labels[i], gbc);
            
            gbc.gridx = 1;
            gbc.weightx = 0.7;
            
            if (i < 7) {
                fields[i].setFont(fieldFont);
                fields[i].setPreferredSize(new Dimension(250, 35));
                panel.add(fields[i], gbc);
            } else {
                panel.add(isActiveCheckBox, gbc);
            }
        }

    }
    
    /**
     * 启用或禁用表单字段
     */
    private void setFormFieldsEnabled(boolean enabled) {
        codeField.setEnabled(enabled);
        nameField.setEnabled(enabled);
        contactPersonField.setEnabled(enabled);
        phoneField.setEnabled(enabled);
        emailField.setEnabled(enabled);
        addressField.setEnabled(enabled);
        creditLimitField.setEnabled(enabled);
        isActiveCheckBox.setEnabled(enabled);
        updateButton.setEnabled(enabled);
    }
    
    /**
     * 添加事件监听器
     */
    private void addEventListeners() {
        // 查询按钮事件
        searchButton.addActionListener(e -> {
            try {
                String idText = idField.getText().trim();
                if (idText.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "请输入客户ID", "输入错误", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                int customerId = Integer.parseInt(idText);
                List<Customers> customersList = SelectCustomers.selectCustomersById(customerId);
                
                if (customersList != null && !customersList.isEmpty()) {
                    Customers customer = customersList.get(0);
                    // 填充表单字段
                    codeField.setText(customer.getCustomerCode());
                    nameField.setText(customer.getCustomerName());
                    contactPersonField.setText(customer.getContactPerson());
                    phoneField.setText(customer.getPhone());
                    emailField.setText(customer.getEmail());
                    addressField.setText(customer.getAddress());
                    creditLimitField.setText(customer.getCreditLimit());
                    isActiveCheckBox.setSelected(customer.getIsActive());
                    
                    // 启用表单字段
                    setFormFieldsEnabled(true);
                } else {
                    JOptionPane.showMessageDialog(this, "未找到ID为 " + customerId + " 的客户记录", 
                            "查找失败", JOptionPane.ERROR_MESSAGE);
                    // 清空并禁用表单字段
                    clearFormFields();
                    setFormFieldsEnabled(false);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
            }
        });
        
        // 更新按钮事件
        updateButton.addActionListener(e -> {
            try {
                int customerId = Integer.parseInt(idField.getText().trim());
                String customerCode = codeField.getText().trim();
                String customerName = nameField.getText().trim();
                String contactPerson = contactPersonField.getText().trim();
                String phone = phoneField.getText().trim();
                String email = emailField.getText().trim();
                String address = addressField.getText().trim();
                String creditLimit = creditLimitField.getText().trim();
                boolean isActive = isActiveCheckBox.isSelected();
                
                // 验证输入
                if (!validateInputs(customerCode, customerName, contactPerson, phone, email, address, creditLimit)) {
                    return;
                }
                
                // 更新客户信息
                if (updateCustomer(customerId, customerCode, customerName, contactPerson, phone, email, address, creditLimit, isActive)) {
                    JOptionPane.showMessageDialog(this, "客户信息更新成功", "更新成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "客户信息更新失败", "更新失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "客户ID格式错误", "输入错误", JOptionPane.WARNING_MESSAGE);
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(e -> {
            dispose();
        });
        
        // 为ID文本框添加回车键事件
        idField.addActionListener(e -> searchButton.doClick());
    }

    private void clearFormFields() {
        codeField.setText("");
        nameField.setText("");
        contactPersonField.setText("");
        phoneField.setText("");
        emailField.setText("");
        addressField.setText("");
        creditLimitField.setText("");
        isActiveCheckBox.setSelected(false);
    }

    private boolean validateInputs(String customerCode, String customerName, String contactPerson,
                                  String phone, String email, String address, String creditLimit) {
        // 1. 校验客户编码
        if (customerCode.isEmpty()) {
            showValidationError("客户编码不能为空");
            return false;
        }
        
        // 2. 校验客户名称
        if (customerName.isEmpty()) {
            showValidationError("客户名称不能为空");
            return false;
        }
        
        // 3. 校验联系人
        if (contactPerson.isEmpty()) {
            showValidationError("联系人不能为空");
            return false;
        }
        
        // 4. 校验联系电话
        if (phone.isEmpty()) {
            showValidationError("联系电话不能为空");
            return false;
        }
        
        // 5. 校验电子邮箱
        if (email.isEmpty()) {
            showValidationError("电子邮箱不能为空");
            return false;
        }
        
        // 验证邮箱格式
        if (email.matches(EMAIL_REGEX)) {
            showValidationError("电子邮箱格式不正确");
            return false;
        }
        
        // 6. 校验联系地址
        if (address.isEmpty()) {
            showValidationError("联系地址不能为空");
            return false;
        }
        
        // 7. 校验信用额度
        if (creditLimit.isEmpty()) {
            showValidationError("信用额度不能为空");
            return false;
        }
        
        try {
            double limit = Double.parseDouble(creditLimit);
            if (limit < 0) {
                showValidationError("信用额度不能为负数");
                return false;
            }
        } catch (NumberFormatException e) {
            showValidationError("信用额度必须是数字");
            return false;
        }
        
        return true;
    }

    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
    }

    private boolean updateCustomer(int customerId, String customerCode, String customerName,
                                  String contactPerson, String phone, String email,
                                  String address, String creditLimit, boolean isActive) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = DBUtils.getConnection();
            String sql = "UPDATE customers SET customer_code=?, customer_name=?, contact_person=?, " +
                    "phone=?, email=?, address=?, credit_limit=?, is_active=?, updated_time=NOW() " +
                    "WHERE customer_id=?";
            
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, customerCode);
            preparedStatement.setString(2, customerName);
            preparedStatement.setString(3, contactPerson);
            preparedStatement.setString(4, phone);
            preparedStatement.setString(5, email);
            preparedStatement.setString(6, address);
            preparedStatement.setString(7, creditLimit);
            preparedStatement.setBoolean(8, isActive);
            preparedStatement.setInt(9, customerId);
            
            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateCustomer::new);
    }
} 